//priority 10000
//以下为物品注册
StartupEvents.registry('item', event => {
    event.create("eou:test_energe")
        .attachCapability(energyItemCapabilityBuilder(10000000, -1, 20000))//最大接受能量为-1则无限制 为0则不能输入能量
        .tooltip("IndexOfShowEnergy")//手动设置能量应该显示的位置

})
/**
 * @param {Number} maxEnergyStored_ 最大能量
 * @param {Number }maxReceiveEnergy_ 最大接受能量/t
 * @param {Number }maxExtractEnergy_ 最大输出能量/t

 * */

//以下为封装好了的能力附加器
function energyItemCapabilityBuilder(maxEnergyStored_, maxReceiveEnergy_, maxExtractEnergy_) {
    var capabilityBuilder = CapabilityBuilder.ENERGY.customItemStack()
    capabilityBuilder
        .getEnergyStored(/**@type {Internal.ItemStack}*/itemStack => {
            if (itemStack.getOrCreateTag().contains("energyStored")) {
                return itemStack.nbt.getInt("energyStored")
            } else {
                itemStack.getOrCreateTag().putInt("energyStored", 0)
                return 0
            }
        })
        .getMaxEnergyStored((/**@type {Internal.ItemStack}*/itemStack) => {
            var maxEnergyStored = maxEnergyStored_
            var { energyStored } = itemStack.getCapability(ForgeCapabilities.ENERGY).orElse(null)
            if (energyStored > maxEnergyStored) {
                itemStack.nbt.putInt("energyStored", maxEnergyStored)
            }

            if (itemStack.nbt.contains("maxEnergyStored")) {
                return itemStack.nbt.getInt("maxEnergyStored")
            } else {
                itemStack.nbt.putInt("maxEnergyStored", maxEnergyStored)
                return maxEnergyStored
            }
        })
        .canReceive((itemStack) => { return maxReceiveEnergy_ == -1 ? true : maxReceiveEnergy_ > 0 })
        .receiveEnergy((/**@type {Internal.ItemStack}*/itemStack, energy, sim) => {
            var { energyStored, maxEnergyStored } = itemStack.getCapability(ForgeCapabilities.ENERGY).orElse(null)
            var receiveEnergy = maxReceiveEnergy_ == -1 ? Math.min(energy, maxEnergyStored - energyStored) : Math.min(energy, maxEnergyStored - energyStored, maxReceiveEnergy_)
            if (!sim) {
                itemStack.nbt.putInt("energyStored", energyStored + receiveEnergy)
            }
            return receiveEnergy
        })
        .canExtract((itemStack) => { return itemStack.getCapability(ForgeCapabilities.ENERGY).orElse(null).energyStored > 0 })
        .extractEnergy((/**@type {Internal.ItemStack}*/itemStack, extractEnergy_, sim) => {
            var { energyStored } = itemStack.getCapability(ForgeCapabilities.ENERGY).orElse(null)
            var extractEnergy = Math.min(maxExtractEnergy_, energyStored, extractEnergy_)
            if (!sim) {
                itemStack.nbt.putInt("energyStored", Math.max(energyStored - extractEnergy, 0))
            }
            return extractEnergy
        })

    return capabilityBuilder
}